if (typeof Object.assign !== 'function') {
	(function () {
		Object.assign = function (target) {
			'use strict';
			if (target === undefined || target === null) {
				throw new TypeError('Cannot convert undefined or null to object');
			}

			var output = Object(target);
			for (var index = 1; index < arguments.length; index++) {
				var source = arguments[index];
				if (source !== undefined && source !== null) {
					for (var nextKey in source) {
						if (source.hasOwnProperty(nextKey)) {
							output[nextKey] = source[nextKey];
						}
					}
				}
			}
			return output;
		};
	})();
}

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var host = '';
var env = false;

var whiteOrder = ['3000', '3001', '8080']
for (var i = 0; i < whiteOrder.length; i++) {
	if (whiteOrder[i] === location.port) {
		env = true;
		host = 'http://testa.yizhuan5.com';
	}
}

var api = {
	toURL: host + '/Common/Tool/ToUrl?data=',
	// 登录
	LoginIn: host + '/Account/Login/LoginIn',
	// 登录状态获取
	UserInfo: host + '/Account/Service/UserInfo',
	// 退出账号
	logout: host + '/Account/Logout/Logout',
	// 验证码
	ValidateCodeSMS: host + '/Common/Tool/ValidateCodeSMS',
	// 注册
	Register: host + '/Account/Login/Register',
	// 重置密码
	ResetPwd: host + '/Account/Login/ResetPwd',
	// 课堂支付
    GetYKShop: host + '/Account/Service/GetYKShop',
	// 课堂订单
    PlaceYKOrder: host + '/Account/Service/PlaceYKOrder',
	// 微信支付
	WeChatPay: host + '/Common/Tool/ToQR_Code?data=',
	// 支付宝订单
    PayYK: host + '/Account/Service/PayYK?type=ali&data=',
    // 支付检测
    IsPay: host + '/Account/Service/IsPay'

	// localStorage封装
};var LS = {
	/**
	 * 是否能够被JSON.parse解析对象、数组
	 * @param str {any}
	 * @returns {boolean}
	 *
	 * 注意不能作用判断JSON !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	 * 因为有些特定情况 只要返回对象就是JSON那可能会有意外的问题
	 * '123'     => 123
	 * '{}'      => {}
	 * 'true'    => true
	 * '[1, 5]'  => [1, 5] JSON里面应该能够有键值对 所以不成立
	 */
	isJSONParseObj: function isJSONParseObj(str) {
		if ((typeof str === 'undefined' ? 'undefined' : _typeof(str)).toLowerCase() === 'string') {
			try {
				var res = JSON.parse(str);
				return res || (typeof res === 'undefined' ? 'undefined' : _typeof(res)).toLowerCase() === 'object';
			} catch (e) {
				return false;
			}
		}
		return false;
	},
	push: function push(key, obj) {
		var val = JSON.parse(this.get(key));

		val.push(obj);
		this.set(key, JSON.stringify(val));
	},
	/**
	 * @description [支持js数组和对象]
	 * @param key
	 * @param value
	 * @param merge [默认合并]
	 * @return {string}
	 */
	set: function set(key, value) {
		var merge = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

		var val = value;
		var oldVal = this.get(key);
		// 在iPhone/iPad上有时设置setItem() 会出现诡异的QUOTA_EXCEEDED_ERR错误;
		// 这是一般在setItem之前，先removeItem();
		if (oldVal !== null) {
			if (merge && oldVal) {
				// 合并属性
				val = Object.assign(oldVal, val);
			}
			this.del(key);
		}
		// 类型 判断是否为数组或对象
		if ((typeof val === 'undefined' ? 'undefined' : _typeof(val)).toLowerCase() === 'object') {
			val = JSON.stringify(val);
		}
		localStorage.setItem(key, val);
	},
	// 空 兼容统一返回null
	get: function get(key) {
		var v = localStorage.getItem(key);
		// 能够被JSONParse解析成对象数组就转换
		if (this.isJSONParseObj(v)) {
			v = JSON.parse(v);
		}
		return v === undefined ? null : v;
	},
	del: function del(key) {
		this.remove(key);
	},
	remove: function remove(key) {
		localStorage.removeItem(key);
	},
	clear: function clear() {
		localStorage.clear();
	}

	// 搜索高亮
};function lightTitle(word, title) {
	var inp = word;
	var temp = '';

	if (inp) {
		var tempArr = title.split('');
		var _iteratorNormalCompletion = true;
		var _didIteratorError = false;
		var _iteratorError = undefined;

		try {
			for (var _iterator = inp[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
				var key = _step.value;

				for (var i = 0; i < tempArr.length; i++) {
					if (key === tempArr[i]) {
						tempArr[i] = '<span style="color:#ff4500">' + tempArr[i] + '</span>';
					}
				}
			}
		} catch (err) {
			_didIteratorError = true;
			_iteratorError = err;
		} finally {
			try {
				if (!_iteratorNormalCompletion && _iterator.return) {
					_iterator.return();
				}
			} finally {
				if (_didIteratorError) {
					// throw _iteratorError;
				}
			}
		}

		temp = tempArr.join('') || title;
	}
	return temp || title;
}
// url拼接
function toURL(url) {
	return api.toURL + url;
}

window.user = LS.get('user') || {};



/* ===================================== */
//  返回顶部
/* ===================================== */
var $backDom = $('.back-top');
$(window).scroll(function (event) {
	var doc = $(document);
	var nowH = doc.scrollTop();
	nowH > 300 ? $backDom.stop().show() : $backDom.stop().hide();
}).trigger('scroll');
$backDom.click(function (e) {
	return $('body, html').animate({ scrollTop: 0 }, 400);
});

/* ===================================== */
//  登录
/* ===================================== */
userInfo();
function userInfo(load) {
	$.ajax({
		url: api.UserInfo,
		type: 'post',
		data: { ajax: true },
		dataType: 'json',
		success: function success(data) {
			if (data.Code === 0 || data.Code === 1) {
				var _userInfo = {};
				_userInfo.AMobile = data.Data.AMobile;
				_userInfo.ANickName = data.Data.ANickName;
				_userInfo.PwdToken = Cookie.get('PwdToken');
				_userInfo.SpreadURL = data.Data.SpreadURL;
				_userInfo.isVip = data.Data.isVip;
				_userInfo.AVIPEndTime = data.Data.AVIPEndTime;
				_userInfo.isYearVip = data.Data.isYearVip;
				_userInfo.DevicesNum = data.Data.DevicesNum;
				_userInfo.login = true;
				_userInfo.rem = $('.el-checkbox__input').hasClass('is-checked');
				_userInfo.Remember = $('.el-checkbox__input').hasClass('is-checked')
				LS.set('user', _userInfo);
				$('.user-phone').html(data.Data.AMobile);
				$('.facility-num').html(data.Data.DevicesNum);
				$('.end-vip').html(data.Data.AVIPEndTime);
				loginIn();
				load && location.reload();
				window.isLogin = true
			} else {
				// 登陆失败调用注销直接移除状态
				unLoginFn();
			}
		}
	});
}
function setUserPassVal () {
	var info = LS.get('user') || {}
	$('#user').val(info.AMobile);
	$('#password').val(info.PwdToken);
}
$('.textP').on('click', '.eye', function () {
	var _this = $(this);
	_this.toggleClass(function () {
		if (_this.is('.icon-view')) {
			_this.removeClass('icon-view').attr({ 'title': '点击遮掩密码' });
			$('#password').attr({ 'type': 'text' });
			return 'icon-eyeoff';
		} else {
			_this.removeClass('icon-eyeoff').attr({ 'title': '点击密码可见' });
			$('#password').attr({ 'type': 'password' });
			return 'icon-view';
		}
	});
	return false;
});
$('.el-checkbox').click(function () {
	var _this = $(this);
	_this.toggleClass('is-checked');
	_this.find('.el-checkbox__input').toggleClass('is-checked');
	return false;
});
function loginFn(event) {
	var sendData = {
		userName: $('#user').val(),
		userPwd: $('#password').val()
	};
	if ($('.checkedbtn').hasClass('is-checked')) {
		sendData.Remember = true;
	}
	if (window.user.PwdToken === $('#password').val()) {
		sendData.token = window.user.PwdToken;
	}
	var _this = $(this);
	$.ajax({
		url: api.LoginIn,
		type: 'post',
		data: sendData,
		dataType: 'json',
		success: function success(data) {
			if (data.Code === 0 || data.Code === 1) {
				userInfo(true);
				$('.login-registry').hide();
			}
			data.Code && layer.msg(data.Msg);
		}
	});
	return false;
}
$('#password').keyup(function (event) {
	if (event.keyCode === 13) {
		loginFn();
	}
});
$('#user').keyup(function (event) {
	if (event.keyCode === 13) {
		loginFn();
	}
});
$('.loginBtn').click(loginFn);
$('.login-registry').on('click', '.cancel', function (e) {
	$('.login-registry').hide();
	return false;
});

// 退出
function unLogin() {
	$('.info-box').hide();
	$('.info-wrap').show();
}
function unLoginFn () {
    window.isLogin = false
	unLogin();
	var info = LS.get('user') || {}
	var temp = {
		login: false,
		AMobile: info.AMobile
	}
	// 有记住密码则不清空
	if (info.PwdToken) {
		temp.PwdToken = info.PwdToken
	}
	LS.set('user', temp);
	// 需要清除的本地cookie
	Cookie.del('PwdToken');
	Cookie.del('Identification');
	Cookie.del('Token');
	Cookie.del('ct');
	// 跳转注销页面让服务器删除cookie
	$.ajax({
		url: api.logout,
		type: 'post',
		dataType: 'json'
	}).then(function (data) {
		// if (location.href.indexOf('/course.html') === -1) location.href = '/course.html';
	});
	return false;
}
function loginIn() {
	$('.info-box').show();
	$('.info-wrap').hide();
}
unLogin();
$('.logout').click(unLoginFn);

// 注册
$('.form .img').click(function () {
	var _this = $(this);
	_this.attr('src', '');
	_this.attr('src', '/Common/Tool/ValidateCode?_=' + Date.now());
	return false;
});
$('.form button').click(function (e) {
	e.preventDefault();
	return false;
});

$('.login').click(function () {
	$('.login-registry').show();
	$('#login').show().siblings().hide();
	setUserPassVal()
});
$('.register').click(function () {
	$('.login-registry').show();
	$('#register').show().siblings().hide();
});
$('.forgetPass').click(function () {
	$('.login-registry').show();
	$('#forget').show().siblings().hide();
});
$('.getMessage').click(function () {
	if ($(this).hasClass('disabled')) return;
	$('.getMessage').addClass('disabled');
	var i = 60;
	$('.getMessage').html('60');
	window.regSendCodeInter = setInterval(function () {
		--i;
		if (!i) {
			clearInterval(window.regSendCodeInter);
			$('.getMessage').removeClass('disabled');
			$('.getMessage').html('重新发送');
		} else {
			$('.getMessage').html(i);
		}
	}, 1000);
	var typeVal = Number($(this).hasClass('reg-code'));
	$.ajax({
		url: api.ValidateCodeSMS,
		data: {
			type: typeVal || 2,
			phone: typeVal ? $('.reg-phone').val() : $('.forget-phone').val(),
			imgCode: typeVal ? $('.reg-code').val() : $('.forget-code').val()
		},
		type: 'post',
		dataType: 'json',
		success: function success(data) {
			if (data.Code === 0 || data.Code === 1) {
				layer.msg('发送成功请注意查收');
			} else {
				i = 0;
				clearInterval(window.regSendCodeInter);
				$('.getMessage').removeClass('disabled');
				$('.getMessage').html('发送短信码');
				typeVal ? $('.isRegister .img').click() : $('.forget .img').click();
			}
			if (data.Code) {
				layer.msg(data.Msg, { anim: 6 });
			}
		}
	});
	return false;
});
// 注册提交
$('.reg-btn').click(function () {
	var sendData = {
		userName: $('.reg-phone').val(),
		userPwd: $('.reg-pass').val(),
		toUserPwd: $('.reg-pass').val(),
		checkCode: $('.reg-msg-code').val()
	};
	$.ajax({
		url: api.Register,
		type: 'post',
		data: sendData,
		dataType: 'json',
		success: function success(data) {
			if (data.Code === 0 || data.Code === 1) {
				$('.login-registry').hide();
				layer.msg('注册成功，祝您体验愉快！');
				setTimeout(function () {
					location.reload();
				}, 700);
			}
			if (data.Code) {
				layer.msg(data.Msg, { anim: 6 });
			}
		}
	});
});
// 重置密码提交
$('.forget-btn').click(function () {
	var sendData = {
		userName: $('.forget-phone').val(),
		userPwd: $('.forget-pass').val(),
		toUserPwd: $('.forget-pass').val(),
		checkCode: $('.forget-msg-code').val(),
		imgCode: $('.forget-code').val()
	};
	$.ajax({
		url: api.ResetPwd,
		type: 'post',
		data: sendData,
		dataType: 'json',
		success: function success(data) {
			if (data.Code === 0 || data.Code === 1) {
				$('.login-registry').hide();
				layer.msg('密码修改成功，请重新登录体验！');
				setTimeout(function () {
					location.reload();
				}, 700);
			}
			if (data.Code) {
				layer.msg(data.Msg, { anim: 6 });
			}
		}
	});
	return false;
});
$('.eye').click(function () {
	var _this = $(this);
	var inp = _this.prev();
	_this.toggleClass(function () {
		if (_this.is('.icon-view')) {
			_this.removeClass('icon-view').attr({ 'title': '点击遮掩密码' });
			inp.attr({ 'type': 'text' });
			return 'icon-eyeoff';
		} else {
			_this.removeClass('icon-eyeoff').attr({ 'title': '点击密码可见' });
			inp.attr({ 'type': 'password' });
			return 'icon-view';
		}
	});
	return false;
});



// 顶部菜单
$(window).scroll(function () {
	var now = $(window).scrollTop();
	if (now > 100) {
		$('#hd, .header-wrap').addClass('hd-shadow');
	} else {
		$('#hd, .header-wrap').removeClass('hd-shadow');
	}
});

/* ===================================== */
//  活动弹层广告
/* ===================================== */
$('#Notice').hide()
// JSON.parse(LS.get('notice') || false) ? $('#Notice').hide() : $('#Notice').show()
// $('.checkbox, .checkbox-label').click(function() {
// 	var $this = $(this)
// 	if ($this.hasClass('checkbox-label')) {
// 		$this = $this.prev()
// 	}
// 	$this.toggleClass('is-checked')
// 	localStorage.notice = $this.hasClass('is-checked')
// })
// $('.notice-close').click(function () {
// 	$('#Notice').hide();
// });



/* ===================================== */
//  支付
/* ===================================== */
$('.method-list').find('li').click(function (event) {
	var $this = $(this)
	$this.addClass('on').siblings().removeClass('on')
})
$(document).on('click', '.close-pay', function (event) {
	payVisible()
})
$(document).on('click', '.buy-vip', function (event) {
	payVisible()
})

$('.buy-course-btn').click(function () {
    payVisible()
})

function payVisible () {
    if (window.isLogin) {
        $('#pay').toggle()
    } else {
        $('.login').click()
    }
}

function isPhone (str) { return /^(?:86|886|)1\d{10}\s*$/.test(str) } // 手机号支持区号

function checkValidity () {
	var user = $('#u').val()
	var tel = $('#t').val()
	var qq = $('#q').val()

	if (!user) {
		layer.msg('您还没有输入姓名!')
		return false
	}
	if (!tel) {
		layer.msg('您还没有输入联系方式!')
		return false
	}
	if (!qq) {
		layer.msg('您还没有输入QQ号码!')
		return false
	}

	return user && tel && qq
}

$('#payBtn').click(function (event) {
    window.method = $('.method-list').find('.on').attr('data-method') * 1
    if (checkValidity()) {
        if (method === 1) {
            window.newTarget = window.open('about:blank')
        }
        placeAnOrder(order.STID).then(function (data) {
            if (data.Code === 0 || data.Code === 1) {
            	window.orderList = data.Data
				// 支付宝
                if (method === 1) {
                    // 支付宝
                    newTarget.location.href = api.PayYK + data.Data.trade_ali
                    layer.open({
                        title: '等待支付',
                        content: '<p style="text-align: center;line-height: 50px; font-size: 16px;">请在新打开的页面中完成支付<p>',
                        btn: ['已完成', '关闭'],
                        btnAlign: 'c',
                        type: 1,
                        area: ['282px', '150px'],
                        yes () {
                            checkPay()
                            return false
                        }
                    })
                } else {
                    // 微信
                    layer.open({
                        title: '等待支付',
                        content: `<p class="tac">
							<img src="${api.WeChatPay + orderList.trade_wx}" style="margin-top: 20px;" alt="" width="180" height="180" />
							<span style="margin-top: 20px; display: inline-block;">请打开微信使用扫一扫进行付款</span>
					  <p>`,
                        btn: ['已完成', '关闭'],
                        btnAlign: 'c',
                        type: 1,
                        area: ['346px', '350px'],
                        yes () {
                            checkPay()
                            return false
                        }
                    })
                }
            }
		})
    }

})

// 获取支付信息
function GetYKShop(load) {
    $.ajax({
        url: api.GetYKShop,
        type: 'post',
        dataType: 'json',
        success: function success(data) {
            if (data.Code === 0 || data.Code === 1) {
            	// 后期可能会改成多课堂订单
				window.order = data.Data[0]
				$('.pay-title span:eq(0)').html(`课程：${order.STName}`)
				$('.pay-title span:eq(1)').html(`¥ ${order.STPrice}.00元`)
				$('.pay-bd-method > p > span:eq(1)').html(`¥${order.STPrice} `)
            }
		}
    });
}
GetYKShop()

// 下单
function placeAnOrder (STID) {
	layer.load({})
	return $.ajax({
		url: api.PlaceYKOrder,
		data: {
			STID: STID,
			nikeName: $('#u').val(),
			mobile: $('#t').val(),
			qq: $('#q').val()
		},
		type: 'post',
		dataType: 'json',
		crossDomain: true,
		xhrFields: { withCredentials: true },
		success: function () { layer.closeAll() }
	})
}

$('.know').click(function () {
    payVisible()
	$('#AIDS')[0].click()
})

// 支付检测
async function checkPay () {
	return $.ajax({
		url: api.IsPay,
		type: 'post',
		data: {
            orderNo: orderList.trade_no,
            type: method === 2 ? 'wx' : 'ali'
		},
		dataType: 'json',
		crossDomain: true,
		xhrFields: { withCredentials: true },
		success: function (data) {
            if (data.Code === 0 || data.Code === 1) {
                layer.closeAll()
                payVisible()
                layer.msg('支付成功！')
            } else {
            	layer.msg(data.Msg, { anim: 6 })
			}
		}
	})
}
